/*
 * @lc app=leetcode.cn id=61 lang=cpp
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head == NULL || head->next == NULL || k==0)
            return head;
        ListNode* p = head;
        ListNode* pre = NULL;
        int count = 1;
        while(p->next!=NULL)
        {
            p = p->next;
            count++;
        }
        k %= count;
        if(k == 0)
            return head;
        
        //挪元素
        p->next = head;
        pre = head;
        int i = 0;
        while(i < count - k - 1)
        {
            pre = pre->next;
            i++;
        }
        p = pre->next;
        pre->next = NULL;
        
        return p;

    }
};
// @lc code=end

